package com.admin.kotlintest.base

import android.annotation.SuppressLint
import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

/**
 * Created by admin on 2017/11/28.
 */

class AdapterHolder (context: Context, group: ViewGroup, viewId: Int, position: Int) {

    private var adapterViews=SparseArray<View>()
    private var position:Int = 0
    private var layoutId:Int = 0

    init {
        contentView = LayoutInflater.from(context).inflate(viewId, group, false)
        contentView?.tag = this
        this.position = position
    }

    @Suppress("UNCHECKED_CAST")
    private fun <T : View> getView(viewId: Int): T? {
        var view: View ? = adapterViews.get(viewId)
        if (view == null) {
            view = contentView?.findViewById<T>(viewId)
            adapterViews.put(viewId, view)
        }
        return view as T
    }

    fun getContentView(): View ?{
        return contentView
    }

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var contentView: View ?=null

        fun getAdapterHolder(context: Context, contentView: View?, group: ViewGroup, viewId: Int, position: Int): AdapterHolder {
            return if (contentView == null) {
                val holder = AdapterHolder(context, group, viewId, position)
                holder.layoutId = viewId
                holder
            } else {
                val holder = contentView.tag as AdapterHolder
                holder.position = position
                holder
            }
        }
    }


    /**
     * 通用的控件设置方法 自此以下
     *
     */

    fun getImageView(viewId: Int): ImageView? {
        return getView(viewId)
    }

    fun getTextView(viewId: Int): TextView? {
        return getView(viewId)
    }

}
